std/io/buffered/bufwriter.rs
1use crate::io::{
2 self, DEFAULT_BUF_SIZE, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write,
3};
4use crate::mem::{self, ManuallyDrop};
5use crate::{error, fmt, ptr};
6
7/// Wraps a writer and buffers its output.
8///
9/// It can be excessively inefficient to work directly with something that
10/// implements [`Write`]. For example, every call to
11/// [`write`][`TcpStream::write`] on [`TcpStream`] results in a system call. A
12/// `BufWriter<W>` keeps an in-memory buffer of data and writes it to an underlying
13/// writer in large, infrequent batches.
14///
15/// `BufWriter<W>` can improve the speed of programs that make *small* and
16/// *repeated* write calls to the same file or network socket. It does not
17/// help when writing very large amounts at once, or writing just one or a few
18/// times. It also provides no advantage when writing to a destination that is
19/// in memory, like a <code>[Vec]\<u8></code>.
20///
21/// It is critical to call [`flush`] before `BufWriter<W>` is dropped. Though
22/// dropping will attempt to flush the contents of the buffer, any errors
23/// that happen in the process of dropping will be ignored. Calling [`flush`]
24/// ensures that the buffer is empty and thus dropping will not even attempt
25/// file operations.
26///
27/// # Examples
28///
29/// Let's write the numbers one through ten to a [`TcpStream`]:
30///
31/// ```no_run
32/// use std::io::prelude::*;
33/// use std::net::TcpStream;
34///
35/// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
36///
37/// for i in 0..10 {
38/// stream.write(&[i+1]).unwrap();
39/// }
40/// ```
41///
42/// Because we're not buffering, we write each one in turn, incurring the
43/// overhead of a system call per byte written. We can fix this with a
44/// `BufWriter<W>`:
45///
46/// ```no_run
47/// use std::io::prelude::*;
48/// use std::io::BufWriter;
49/// use std::net::TcpStream;
50///
51/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
52///
53/// for i in 0..10 {
54/// stream.write(&[i+1]).unwrap();
55/// }
56/// stream.flush().unwrap();
57/// ```
58///
59/// By wrapping the stream with a `BufWriter<W>`, these ten writes are all grouped
60/// together by the buffer and will all be written out in one system call when
61/// the `stream` is flushed.
62///
63/// [`TcpStream::write`]: crate::net::TcpStream::write
64/// [`TcpStream`]: crate::net::TcpStream
65/// [`flush`]: BufWriter::flush
66#[stable(feature = "rust1", since = "1.0.0")]
67pub struct BufWriter<W: ?Sized + Write> {
68 // The buffer. Avoid using this like a normal `Vec` in common code paths.
69 // That is, don't use `buf.push`, `buf.extend_from_slice`, or any other
70 // methods that require bounds checking or the like. This makes an enormous
71 // difference to performance (we may want to stop using a `Vec` entirely).
72 buf: Vec<u8>,
73 // #30888: If the inner writer panics in a call to write, we don't want to
74 // write the buffered data a second time in BufWriter's destructor. This
75 // flag tells the Drop impl if it should skip the flush.
76 panicked: bool,
77 inner: W,
78}
79
80impl<W: Write> BufWriter<W> {
81 /// Creates a new `BufWriter<W>` with a default buffer capacity. The default is currently 8 KiB,
82 /// but may change in the future.
83 ///
84 /// # Examples
85 ///
86 /// ```no_run
87 /// use std::io::BufWriter;
88 /// use std::net::TcpStream;
89 ///
90 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
91 /// ```
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub fn new(inner: W) -> BufWriter<W> {
94 BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
95 }
96
97 pub(crate) fn try_new_buffer() -> io::Result<Vec<u8>> {
98 Vec::try_with_capacity(DEFAULT_BUF_SIZE).map_err(|_| {
99 io::const_error!(ErrorKind::OutOfMemory, "failed to allocate write buffer")
100 })
101 }
102
103 pub(crate) fn with_buffer(inner: W, buf: Vec<u8>) -> Self {
104 Self { inner, buf, panicked: false }
105 }
106
107 /// Creates a new `BufWriter<W>` with at least the specified buffer capacity.
108 ///
109 /// # Examples
110 ///
111 /// Creating a buffer with a buffer of at least a hundred bytes.
112 ///
113 /// ```no_run
114 /// use std::io::BufWriter;
115 /// use std::net::TcpStream;
116 ///
117 /// let stream = TcpStream::connect("127.0.0.1:34254").unwrap();
118 /// let mut buffer = BufWriter::with_capacity(100, stream);
119 /// ```
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
122 BufWriter { inner, buf: Vec::with_capacity(capacity), panicked: false }
123 }
124
125 /// Unwraps this `BufWriter<W>`, returning the underlying writer.
126 ///
127 /// The buffer is written out before returning the writer.
128 ///
129 /// # Errors
130 ///
131 /// An [`Err`] will be returned if an error occurs while flushing the buffer.
132 ///
133 /// # Examples
134 ///
135 /// ```no_run
136 /// use std::io::BufWriter;
137 /// use std::net::TcpStream;
138 ///
139 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
140 ///
141 /// // unwrap the TcpStream and flush the buffer
142 /// let stream = buffer.into_inner().unwrap();
143 /// ```
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
146 match self.flush_buf() {
147 Err(e) => Err(IntoInnerError::new(self, e)),
148 Ok(()) => Ok(self.into_parts().0),
149 }
150 }
151
152 /// Disassembles this `BufWriter<W>`, returning the underlying writer, and any buffered but
153 /// unwritten data.
154 ///
155 /// If the underlying writer panicked, it is not known what portion of the data was written.
156 /// In this case, we return `WriterPanicked` for the buffered data (from which the buffer
157 /// contents can still be recovered).
158 ///
159 /// `into_parts` makes no attempt to flush data and cannot fail.
160 ///
161 /// # Examples
162 ///
163 /// ```
164 /// use std::io::{BufWriter, Write};
165 ///
166 /// let mut buffer = [0u8; 10];
167 /// let mut stream = BufWriter::new(buffer.as_mut());
168 /// write!(stream, "too much data").unwrap();
169 /// stream.flush().expect_err("it doesn't fit");
170 /// let (recovered_writer, buffered_data) = stream.into_parts();
171 /// assert_eq!(recovered_writer.len(), 0);
172 /// assert_eq!(&buffered_data.unwrap(), b"ata");
173 /// ```
174 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
175 pub fn into_parts(self) -> (W, Result<Vec<u8>, WriterPanicked>) {
176 let mut this = ManuallyDrop::new(self);
177 let buf = mem::take(&mut this.buf);
178 let buf = if !this.panicked { Ok(buf) } else { Err(WriterPanicked { buf }) };
179
180 // SAFETY: double-drops are prevented by putting `this` in a ManuallyDrop that is never dropped
181 let inner = unsafe { ptr::read(&this.inner) };
182
183 (inner, buf)
184 }
185}
186
187impl<W: ?Sized + Write> BufWriter<W> {
188 /// Send data in our local buffer into the inner writer, looping as
189 /// necessary until either it's all been sent or an error occurs.
190 ///
191 /// Because all the data in the buffer has been reported to our owner as
192 /// "successfully written" (by returning nonzero success values from
193 /// `write`), any 0-length writes from `inner` must be reported as i/o
194 /// errors from this method.
195 pub(in crate::io) fn flush_buf(&mut self) -> io::Result<()> {
196 // SAFETY: `<BufWriter as BufferedWriterSpec>::copy_from` assumes that
197 // this will not de-initialize any elements of `self.buf`'s spare
198 // capacity.
199
200 /// Helper struct to ensure the buffer is updated after all the writes
201 /// are complete. It tracks the number of written bytes and drains them
202 /// all from the front of the buffer when dropped.
203 struct BufGuard<'a> {
204 buffer: &'a mut Vec<u8>,
205 written: usize,
206 }
207
208 impl<'a> BufGuard<'a> {
209 fn new(buffer: &'a mut Vec<u8>) -> Self {
210 Self { buffer, written: 0 }
211 }
212
213 /// The unwritten part of the buffer
214 fn remaining(&self) -> &[u8] {
215 &self.buffer[self.written..]
216 }
217
218 /// Flag some bytes as removed from the front of the buffer
219 fn consume(&mut self, amt: usize) {
220 self.written += amt;
221 }
222
223 /// true if all of the bytes have been written
224 fn done(&self) -> bool {
225 self.written >= self.buffer.len()
226 }
227 }
228
229 impl Drop for BufGuard<'_> {
230 fn drop(&mut self) {
231 if self.written > 0 {
232 // Like `self.buffer.drain(..self.written)` but more obviously
233 // preserving the spare capacity; see note above.
234 let new_len = self.buffer.len() - self.written;
235 // SAFETY: Assumes `Vec::as_mut_slice` will not
236 // de-initialize any elements of `self.buf`'s spare capacity,
237 // and that `<&mut [u8]>::copy_within` will not do so either.
238 self.buffer.as_mut_slice().copy_within(self.written.., 0);
239 // SAFETY: Assumes `Vec::truncate` will not de-initialize
240 // any elements of `self.buf`'s spare capacity,
241 self.buffer.truncate(new_len);
242 }
243 }
244 }
245
246 let mut guard = BufGuard::new(&mut self.buf);
247 while !guard.done() {
248 self.panicked = true;
249 let r = self.inner.write(guard.remaining());
250 self.panicked = false;
251
252 match r {
253 Ok(0) => {
254 return Err(io::const_error!(
255 ErrorKind::WriteZero,
256 "failed to write the buffered data",
257 ));
258 }
259 Ok(n) => guard.consume(n),
260 Err(ref e) if e.is_interrupted() => {}
261 Err(e) => return Err(e),
262 }
263 }
264 Ok(())
265 }
266
267 /// Buffer some data without flushing it, regardless of the size of the
268 /// data. Writes as much as possible without exceeding capacity. Returns
269 /// the number of bytes written.
270 pub(super) fn write_to_buf(&mut self, buf: &[u8]) -> usize {
271 let available = self.spare_capacity();
272 let amt_to_buffer = available.min(buf.len());
273
274 // SAFETY: `amt_to_buffer` is <= buffer's spare capacity by construction.
275 unsafe {
276 self.write_to_buffer_unchecked(&buf[..amt_to_buffer]);
277 }
278
279 amt_to_buffer
280 }
281
282 /// Gets a reference to the underlying writer.
283 ///
284 /// # Examples
285 ///
286 /// ```no_run
287 /// use std::io::BufWriter;
288 /// use std::net::TcpStream;
289 ///
290 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
291 ///
292 /// // we can use reference just like buffer
293 /// let reference = buffer.get_ref();
294 /// ```
295 #[stable(feature = "rust1", since = "1.0.0")]
296 pub fn get_ref(&self) -> &W {
297 &self.inner
298 }
299
300 /// Gets a mutable reference to the underlying writer.
301 ///
302 /// It is inadvisable to directly write to the underlying writer.
303 ///
304 /// # Examples
305 ///
306 /// ```no_run
307 /// use std::io::BufWriter;
308 /// use std::net::TcpStream;
309 ///
310 /// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
311 ///
312 /// // we can use reference just like buffer
313 /// let reference = buffer.get_mut();
314 /// ```
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub fn get_mut(&mut self) -> &mut W {
317 &mut self.inner
318 }
319
320 /// Returns a reference to the internally buffered data.
321 ///
322 /// # Examples
323 ///
324 /// ```no_run
325 /// use std::io::BufWriter;
326 /// use std::net::TcpStream;
327 ///
328 /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
329 ///
330 /// // See how many bytes are currently buffered
331 /// let bytes_buffered = buf_writer.buffer().len();
332 /// ```
333 #[stable(feature = "bufreader_buffer", since = "1.37.0")]
334 pub fn buffer(&self) -> &[u8] {
335 &self.buf
336 }
337
338 /// Returns a mutable reference to the internal buffer.
339 ///
340 /// This can be used to write data directly into the buffer without triggering writers
341 /// to the underlying writer.
342 ///
343 /// That the buffer is a `Vec` is an implementation detail.
344 /// Callers should not modify the capacity as there currently is no public API to do so
345 /// and thus any capacity changes would be unexpected by the user.
346 pub(in crate::io) fn buffer_mut(&mut self) -> &mut Vec<u8> {
347 &mut self.buf
348 }
349
350 /// Returns the number of bytes the internal buffer can hold without flushing.
351 ///
352 /// # Examples
353 ///
354 /// ```no_run
355 /// use std::io::BufWriter;
356 /// use std::net::TcpStream;
357 ///
358 /// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
359 ///
360 /// // Check the capacity of the inner buffer
361 /// let capacity = buf_writer.capacity();
362 /// // Calculate how many bytes can be written without flushing
363 /// let without_flush = capacity - buf_writer.buffer().len();
364 /// ```
365 #[stable(feature = "buffered_io_capacity", since = "1.46.0")]
366 pub fn capacity(&self) -> usize {
367 self.buf.capacity()
368 }
369
370 // Ensure this function does not get inlined into `write`, so that it
371 // remains inlineable and its common path remains as short as possible.
372 // If this function ends up being called frequently relative to `write`,
373 // it's likely a sign that the client is using an improperly sized buffer
374 // or their write patterns are somewhat pathological.
375 #[cold]
376 #[inline(never)]
377 fn write_cold(&mut self, buf: &[u8]) -> io::Result<usize> {
378 if buf.len() > self.spare_capacity() {
379 self.flush_buf()?;
380 }
381
382 // Why not len > capacity? To avoid a needless trip through the buffer when the input
383 // exactly fills it. We'd just need to flush it to the underlying writer anyway.
384 if buf.len() >= self.buf.capacity() {
385 self.panicked = true;
386 let r = self.get_mut().write(buf);
387 self.panicked = false;
388 r
389 } else {
390 // Write to the buffer. In this case, we write to the buffer even if it fills it
391 // exactly. Doing otherwise would mean flushing the buffer, then writing this
392 // input to the inner writer, which in many cases would be a worse strategy.
393
394 // SAFETY: There was either enough spare capacity already, or there wasn't and we
395 // flushed the buffer to ensure that there is. In the latter case, we know that there
396 // is because flushing ensured that our entire buffer is spare capacity, and we entered
397 // this block because the input buffer length is less than that capacity. In either
398 // case, it's safe to write the input buffer to our buffer.
399 unsafe {
400 self.write_to_buffer_unchecked(buf);
401 }
402
403 Ok(buf.len())
404 }
405 }
406
407 // Ensure this function does not get inlined into `write_all`, so that it
408 // remains inlineable and its common path remains as short as possible.
409 // If this function ends up being called frequently relative to `write_all`,
410 // it's likely a sign that the client is using an improperly sized buffer
411 // or their write patterns are somewhat pathological.
412 #[cold]
413 #[inline(never)]
414 fn write_all_cold(&mut self, buf: &[u8]) -> io::Result<()> {
415 // Normally, `write_all` just calls `write` in a loop. We can do better
416 // by calling `self.get_mut().write_all()` directly, which avoids
417 // round trips through the buffer in the event of a series of partial
418 // writes in some circumstances.
419
420 if buf.len() > self.spare_capacity() {
421 self.flush_buf()?;
422 }
423
424 // Why not len > capacity? To avoid a needless trip through the buffer when the input
425 // exactly fills it. We'd just need to flush it to the underlying writer anyway.
426 if buf.len() >= self.buf.capacity() {
427 self.panicked = true;
428 let r = self.get_mut().write_all(buf);
429 self.panicked = false;
430 r
431 } else {
432 // Write to the buffer. In this case, we write to the buffer even if it fills it
433 // exactly. Doing otherwise would mean flushing the buffer, then writing this
434 // input to the inner writer, which in many cases would be a worse strategy.
435
436 // SAFETY: There was either enough spare capacity already, or there wasn't and we
437 // flushed the buffer to ensure that there is. In the latter case, we know that there
438 // is because flushing ensured that our entire buffer is spare capacity, and we entered
439 // this block because the input buffer length is less than that capacity. In either
440 // case, it's safe to write the input buffer to our buffer.
441 unsafe {
442 self.write_to_buffer_unchecked(buf);
443 }
444
445 Ok(())
446 }
447 }
448
449 // SAFETY: Requires `buf.len() <= self.buf.capacity() - self.buf.len()`,
450 // i.e., that input buffer length is less than or equal to spare capacity.
451 #[inline]
452 unsafe fn write_to_buffer_unchecked(&mut self, buf: &[u8]) {
453 debug_assert!(buf.len() <= self.spare_capacity());
454 let old_len = self.buf.len();
455 let buf_len = buf.len();
456 let src = buf.as_ptr();
457 unsafe {
458 let dst = self.buf.as_mut_ptr().add(old_len);
459 ptr::copy_nonoverlapping(src, dst, buf_len);
460 self.buf.set_len(old_len + buf_len);
461 }
462 }
463
464 #[inline]
465 fn spare_capacity(&self) -> usize {
466 self.buf.capacity() - self.buf.len()
467 }
468}
469
470#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
471/// Error returned for the buffered data from `BufWriter::into_parts`, when the underlying
472/// writer has previously panicked. Contains the (possibly partly written) buffered data.
473///
474/// # Example
475///
476/// ```
477/// use std::io::{self, BufWriter, Write};
478/// use std::panic::{catch_unwind, AssertUnwindSafe};
479///
480/// struct PanickingWriter;
481/// impl Write for PanickingWriter {
482/// fn write(&mut self, buf: &[u8]) -> io::Result<usize> { panic!() }
483/// fn flush(&mut self) -> io::Result<()> { panic!() }
484/// }
485///
486/// let mut stream = BufWriter::new(PanickingWriter);
487/// write!(stream, "some data").unwrap();
488/// let result = catch_unwind(AssertUnwindSafe(|| {
489/// stream.flush().unwrap()
490/// }));
491/// assert!(result.is_err());
492/// let (recovered_writer, buffered_data) = stream.into_parts();
493/// assert!(matches!(recovered_writer, PanickingWriter));
494/// assert_eq!(buffered_data.unwrap_err().into_inner(), b"some data");
495/// ```
496pub struct WriterPanicked {
497 buf: Vec<u8>,
498}
499
500impl WriterPanicked {
501 /// Returns the perhaps-unwritten data. Some of this data may have been written by the
502 /// panicking call(s) to the underlying writer, so simply writing it again is not a good idea.
503 #[must_use = "`self` will be dropped if the result is not used"]
504 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
505 pub fn into_inner(self) -> Vec<u8> {
506 self.buf
507 }
508}
509
510#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
511impl error::Error for WriterPanicked {}
512
513#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
514impl fmt::Display for WriterPanicked {
515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516 "BufWriter inner writer panicked, what data remains unwritten is not known".fmt(f)
517 }
518}
519
520#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
521impl fmt::Debug for WriterPanicked {
522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
523 f.debug_struct("WriterPanicked")
524 .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
525 .finish()
526 }
527}
528
529#[stable(feature = "rust1", since = "1.0.0")]
530impl<W: ?Sized + Write> Write for BufWriter<W> {
531 #[inline]
532 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
533 // Use < instead of <= to avoid a needless trip through the buffer in some cases.
534 // See `write_cold` for details.
535 if buf.len() < self.spare_capacity() {
536 // SAFETY: safe by above conditional.
537 unsafe {
538 self.write_to_buffer_unchecked(buf);
539 }
540
541 Ok(buf.len())
542 } else {
543 self.write_cold(buf)
544 }
545 }
546
547 #[inline]
548 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
549 // Use < instead of <= to avoid a needless trip through the buffer in some cases.
550 // See `write_all_cold` for details.
551 if buf.len() < self.spare_capacity() {
552 // SAFETY: safe by above conditional.
553 unsafe {
554 self.write_to_buffer_unchecked(buf);
555 }
556
557 Ok(())
558 } else {
559 self.write_all_cold(buf)
560 }
561 }
562
563 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
564 // FIXME: Consider applying `#[inline]` / `#[inline(never)]` optimizations already applied
565 // to `write` and `write_all`. The performance benefits can be significant. See #79930.
566 if self.get_ref().is_write_vectored() {
567 // We have to handle the possibility that the total length of the buffers overflows
568 // `usize` (even though this can only happen if multiple `IoSlice`s reference the
569 // same underlying buffer, as otherwise the buffers wouldn't fit in memory). If the
570 // computation overflows, then surely the input cannot fit in our buffer, so we forward
571 // to the inner writer's `write_vectored` method to let it handle it appropriately.
572 let mut saturated_total_len: usize = 0;
573
574 for buf in bufs {
575 saturated_total_len = saturated_total_len.saturating_add(buf.len());
576
577 if saturated_total_len > self.spare_capacity() && !self.buf.is_empty() {
578 // Flush if the total length of the input exceeds our buffer's spare capacity.
579 // If we would have overflowed, this condition also holds, and we need to flush.
580 self.flush_buf()?;
581 }
582
583 if saturated_total_len >= self.buf.capacity() {
584 // Forward to our inner writer if the total length of the input is greater than or
585 // equal to our buffer capacity. If we would have overflowed, this condition also
586 // holds, and we punt to the inner writer.
587 self.panicked = true;
588 let r = self.get_mut().write_vectored(bufs);
589 self.panicked = false;
590 return r;
591 }
592 }
593
594 // `saturated_total_len < self.buf.capacity()` implies that we did not saturate.
595
596 // SAFETY: We checked whether or not the spare capacity was large enough above. If
597 // it was, then we're safe already. If it wasn't, we flushed, making sufficient
598 // room for any input <= the buffer size, which includes this input.
599 unsafe {
600 bufs.iter().for_each(|b| self.write_to_buffer_unchecked(b));
601 };
602
603 Ok(saturated_total_len)
604 } else {
605 let mut iter = bufs.iter();
606 let mut total_written = if let Some(buf) = iter.by_ref().find(|&buf| !buf.is_empty()) {
607 // This is the first non-empty slice to write, so if it does
608 // not fit in the buffer, we still get to flush and proceed.
609 if buf.len() > self.spare_capacity() {
610 self.flush_buf()?;
611 }
612 if buf.len() >= self.buf.capacity() {
613 // The slice is at least as large as the buffering capacity,
614 // so it's better to write it directly, bypassing the buffer.
615 self.panicked = true;
616 let r = self.get_mut().write(buf);
617 self.panicked = false;
618 return r;
619 } else {
620 // SAFETY: We checked whether or not the spare capacity was large enough above.
621 // If it was, then we're safe already. If it wasn't, we flushed, making
622 // sufficient room for any input <= the buffer size, which includes this input.
623 unsafe {
624 self.write_to_buffer_unchecked(buf);
625 }
626
627 buf.len()
628 }
629 } else {
630 return Ok(0);
631 };
632 debug_assert!(total_written != 0);
633 for buf in iter {
634 if buf.len() <= self.spare_capacity() {
635 // SAFETY: safe by above conditional.
636 unsafe {
637 self.write_to_buffer_unchecked(buf);
638 }
639
640 // This cannot overflow `usize`. If we are here, we've written all of the bytes
641 // so far to our buffer, and we've ensured that we never exceed the buffer's
642 // capacity. Therefore, `total_written` <= `self.buf.capacity()` <= `usize::MAX`.
643 total_written += buf.len();
644 } else {
645 break;
646 }
647 }
648 Ok(total_written)
649 }
650 }
651
652 fn is_write_vectored(&self) -> bool {
653 true
654 }
655
656 fn flush(&mut self) -> io::Result<()> {
657 self.flush_buf()?;
658 self.get_mut().flush()
659 }
660}
661
662#[stable(feature = "rust1", since = "1.0.0")]
663impl<W: ?Sized + Write> fmt::Debug for BufWriter<W>
664where
665 W: fmt::Debug,
666{
667 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
668 fmt.debug_struct("BufWriter")
669 .field("writer", &&self.inner)
670 .field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
671 .finish()
672 }
673}
674
675#[stable(feature = "rust1", since = "1.0.0")]
676impl<W: ?Sized + Write + Seek> Seek for BufWriter<W> {
677 /// Seek to the offset, in bytes, in the underlying writer.
678 ///
679 /// Seeking always writes out the internal buffer before seeking.
680 fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
681 self.flush_buf()?;
682 self.get_mut().seek(pos)
683 }
684}
685
686#[stable(feature = "rust1", since = "1.0.0")]
687impl<W: ?Sized + Write> Drop for BufWriter<W> {
688 fn drop(&mut self) {
689 if !self.panicked {
690 // dtors should not panic, so we ignore a failed flush
691 let _r = self.flush_buf();
692 }
693 }
694}